﻿using System;
using System.Collections.Generic;
using System.Web;


namespace CCPSIP.AB
{
    /// <summary>CCPSIP_009：下載個人通訊錄清單 API (v2014-06)</summary>
    /// idHeader = 裝置 UUID 前八碼。iOS 請使用 [CCPCrypto getIdHeader] 呼叫。
    /// checkcode = 裝置限時驗證碼。iOS 請使用 [CCPCrypto getCheckcode] 呼叫。

    public class contact_list : IHttpHandler
    {
        private static List<string> kSIPCamAllowList = new List<string>() { "10384", "17467", "17528" };


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";


            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
                }


                List<ContactGroup> GroupList = new List<ContactGroup>();
                ContactUser[] ContactArray = null;


                if (SipKit.isCCPUser(userInfo.UserType))
                {
                    //【02-1】抓取CCP通訊錄 - 總公司各部門
                    //
                    Dictionary<string, string>[] infoArray = OracleKitContact.getCCPHQContacts(userInfo);
                    List<ContactUser> cList = new List<ContactUser>();

                    for (int i = 0; i < infoArray.Length; i++)
                    {
                        Dictionary<string, string> cInfo = infoArray[i];
                        cList.Add(new ContactUser(cInfo));

                        string thisDeptNo = cInfo["DEPT_NO_MAIN"];
                        if (i == infoArray.Length - 1 || thisDeptNo != infoArray[i + 1]["DEPT_NO_MAIN"])
                        {
                            string groupID = string.Format("HQ_{0}", thisDeptNo);
                            string groupName = string.Format("{0} {1}", thisDeptNo, PersonKit.getDeptCName(thisDeptNo));
                            GroupList.Add(new ContactGroup(groupID, groupName, cList.ToArray()));
                            cList = new List<ContactUser>();
                        }
                    }


                    //【02-2-1】抓取CCP通訊錄 - 大連
                    //
                    ContactArray = OracleKitContact.getDCCContacts(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("DCC", "大連", ContactArray));


                    //【02-2-2】抓取CCP通訊錄 - 長捷士
                    //
                    ContactArray = OracleKitContact.getRCCTContacts(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("RCCT", "長捷士", ContactArray));


                    //【02-2-3】抓取CCP通訊錄 - 長江
                    //
                    ContactArray = OracleKitContact.getChangChiangContacts(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("ChangChiang", "長江", ContactArray));


                    //【02-2-4】抓取CCP通訊錄 - 長春日本
                    //
                    ContactArray = OracleKitContact.getCCPJContacts(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("CCPJ", "長春日本", ContactArray));



                    //【02-3-1】抓取CCP通訊錄 - 新竹廠
                    //
                    ContactArray = OracleKitContact.getFirmSContacts(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("HsinChu", "新竹廠", ContactArray));


                    //【02-3-2】抓取CCP通訊錄 - 苗栗廠
                    //
                    ContactArray = OracleKitContact.getFirmMContacts(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("MiaoLi", "苗栗廠", ContactArray));


                    //【02-3-3】抓取CCP通訊錄 - 彰濱廠
                    //
                    ContactArray = OracleKitContact.getFirmCContacts(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("ChangBing", "彰濱廠", ContactArray));


                    //【02-3-4】抓取CCP通訊錄 - 麥寮廠
                    //
                    ContactArray = OracleKitContact.getFirmLContacts(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("MaiLiao", "麥寮廠", ContactArray));


                    //【02-3-5】抓取CCP通訊錄 - 高雄廠
                    //
                    ContactArray = OracleKitContact.getFirmKContacts(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("KaoHsiung", "高雄廠", ContactArray));


                    //【02-3-6】抓取CCP通訊錄 - 大發廠
                    //
                    ContactArray = OracleKitContact.getFirmDContacts(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("DaFa", "大發廠", ContactArray));


                    //【02-3-7】抓取CCP通訊錄 - 漳州廠
                    //
                    ContactArray = OracleKitContact.getFirmAContacts(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("ZhangZhou", "漳州廠", ContactArray));

                    //【02-3-8】抓取CCP通訊錄 - 新加坡廠
                    //
                    ContactArray = OracleKitContact.getFirmSPContacts(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("Singapore", "新加坡廠", ContactArray));

                    //【02-3-9】抓取CCP通訊錄 - 台豐
                    //
                    ContactArray = OracleKitContact.getFirmTFContacts(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("TaiFung", "台豐", ContactArray));

                    //【02-3-10】抓取CCP通訊錄 - 奇美油倉
                    //
                    ContactArray = OracleKitContact.getFirmCMContacts(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("Chimei", "奇美油倉", ContactArray));


                    //【02-3-99】抓取CCP通訊錄 - 其他(工廠與據點)
                    //
                    ContactArray = OracleKitContact.getOtherContacts(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("Others", "其他據點", ContactArray));


                    //【02-4】抓取個人通訊錄 - 客戶,供應商,代理商,個人朋友
                    //
                    ContactArray = OracleKitContact.getCustomers(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("Customers", "Customers", ContactArray));

                    ContactArray = OracleKitContact.getVendors(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("Vendors", "Vendors", ContactArray));

                    ContactArray = OracleKitContact.getAgents(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("Agents", "Agents", ContactArray));

                    ContactArray = OracleKitContact.getPersons(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("Friends", "Friends", ContactArray));
                }
                else
                {
                    //【03-1】外部會員：CCP朋友
                    //
                    ContactArray = OracleKitContact.getCCPFriendsOfGuest(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("CCP", "CCP Friends", ContactArray));


                    //【03-2】外部會員：其他朋友
                    //
                    ContactArray = OracleKitContact.getOtherFriendsOfGuest(userInfo);
                    if (ContactArray.Length > 0)
                        GroupList.Add(new ContactGroup("Others", "Other Friends", ContactArray));
                }


                //【Debug】測試：資訊中心SIP Cam
                //
                if (kSIPCamAllowList.Contains(userInfo.PPS_CODE))
                {
                    List<ContactUser> ContactList = new List<ContactUser>();
                    ContactList.Add(new ContactUser("889837", "7樓機房Cam"));
                    ContactList.Add(new ContactUser("889838", "5樓資訊中心Cam"));
                    ContactList.Add(new ContactUser("889839", "4樓資訊中心Cam"));
                    GroupList.Add(new ContactGroup("SIPCam", "SIP攝影機", ContactList.ToArray()));
                }


                //【99】回傳結果
                //
                resp.ContentType = "application/json";
                resp.Charset = null;
                fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                resultStr = fastJSON.JSON.Instance.ToJSON(GroupList);
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }


        /// <summary>
        /// 通訊錄群組
        /// </summary>
        private class ContactGroup
        {
            private string _GroupID;
            private string _GroupName;
            private ContactUser[] _Contacts;

            public string GroupID { get { return this._GroupID; } }
            public string GroupName { get { return this._GroupName; } }
            public ContactUser[] Contacts { get { return this._Contacts; } }

            public ContactGroup(string groupID, string groupName, ContactUser[] contacts)
            {
                _GroupID = groupID;
                _GroupName = string.Format("{0} ({1})", groupName, contacts.Length);
                _Contacts = contacts;
            }
        }

    }
}
